//
//  BTSocketViewController.m
//  BaseTools
//
//  Created by 李挺哲 on 15/9/1.
//  Copyright (c) 2015年 ltz. All rights reserved.
//
#define SRV_CONNECTED 0
#define SRV_CONNECT_SUC 1
#define SRV_CONNECT_FAIL 2
#define HOST_PORT 8405
#import "AsyncSocket.h"
#import "BTSocketViewController.h"

@interface BTSocketViewController (){
    
    AsyncSocket *client;
    
    
}
@property (weak, nonatomic) IBOutlet UITextField *ipText;
@property (weak, nonatomic) IBOutlet UITextField *portText;
@property (weak, nonatomic) IBOutlet UITextField *msgText;
@property (weak, nonatomic) IBOutlet UILabel *receiveMsgLabel;
@property(assign,nonatomic) int  status;
@end

@implementation BTSocketViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNavigationTitle:@"SOCKET(TCP)" barTintColor:0x1E86CB titleColor:0xFFFFFF isTranslucent:NO isHidden:NO];
    [self showNavigationLeftButtonTitle:@"返回" tintColor:0xFFFFFF];
    _ipText.text=@"127.0.0.1";
    _portText.text=@"9999";
   _status= [self connectServer:_ipText.text port:_portText.text.intValue];
    NSLog(@"_status  %d",_status);
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)sendAction:(id)sender {
    
    _receiveMsgLabel.text=@"";
    if (_ipText.text.length>0&&_portText.text.length>0&&_msgText.text.length>0) {
        
        if (_status!=SRV_CONNECT_FAIL) {
             [self sendSocketMessage:_msgText.text];
        }
        else{
            
             [self showAlertView:@"检查连接"];
        }
    }
    
    
    
    else{
        
        [self showAlertView:@"请输入必要信息"];
        
    }
    
    
    
    
    
}



- (IBAction)reConnectAction:(id)sender {
    
     _status = [self connectServer:_ipText.text port:_portText.text.intValue];
    NSLog(@"status %d ",_status);
    switch (_status) {
        case SRV_CONNECT_SUC:
            [self showAlertView:@"链接成功"];
            break;
        case SRV_CONNECTED:
            [self showAlertView:@"已连接，无需重连"];
            break;
        default:
            break;
    }
    
    
    
    
}

- (int) connectServer: (NSString *) hostIP port:(int) hostPort{
    
    if (client == nil) {
        client = [[AsyncSocket alloc] initWithDelegate:self];
        NSError *err = nil;
        //192.168.110.128
        if (![client connectToHost:hostIP onPort:hostPort error:&err]) {
            NSLog(@"%ld %@", (long)[err code], [err localizedDescription]);
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host "
                                                                     stringByAppendingString:hostIP]
                                                            message:[[[NSString alloc]initWithFormat:@"%ld",(long)[err code]] stringByAppendingString:[err localizedDescription]]
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            
            //client = nil;
            return SRV_CONNECT_FAIL;
        } else {
            NSLog(@"Conected!");
            return SRV_CONNECT_SUC;
        }
    }
    else {
        [client readDataWithTimeout:-1 tag:0];
        return SRV_CONNECTED;
    }
    
}
-(void)sendSocketMessage :(NSString *) msg{
    [self showIndicatorView:@"发送中"];
    NSString * content = [msg stringByAppendingString:@"\r\n"];
    NSLog(@"%@",content);
    NSData *data = [content dataUsingEncoding:NSISOLatin1StringEncoding];
    [client writeData:data withTimeout:-1 tag:0];
    
    
}


- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
    [client readDataWithTimeout:-1 tag:0];
}

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    NSLog(@"Error");
    _status=SRV_CONNECT_FAIL;
    
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
    
    
    [self dismissIndicatorView];
    NSString *msg = @"Sorry this connect is failure";
    NSLog(@"%@",msg);
    _status=SRV_CONNECT_FAIL;

    [self showBottomAlertView:msg];
    
    
    client = nil;
}

- (void)onSocketDidSecure:(AsyncSocket *)sock{
    
}

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    
    NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"server received datas is :%@",aStr);
    [client readDataWithTimeout:-1 tag:0];
    if (aStr) {
        
        [self dismissIndicatorView];
        NSLog(aStr);
        _receiveMsgLabel.text=aStr;
    }
    
    
    
}



//UDP





@end
